<template>
  <div class="search-container">
    <!-- 顶部的搜索栏 -->
    <!-- Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。没有form标签 则在移动端输入法不会显示搜索 -->
    <form action="/" class="searchForm">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        background="#3296fa"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result
      v-if="isResultShow"
      :search-text="searchText"
    ></search-result>
    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    ></search-suggestion>
    <!-- 搜索历史记录 -->
    <search-history
      v-else
      :search-history="searchHistory"
      @clear-search-history="searchHistory = []"
      @search="onSearch"
    ></search-history>
  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
import { setItem, getItem } from '../../utils/storage'
export default {
  name: 'searchIndex',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  props: {},
  data() {
    return {
      isResultShow: false,
      searchText: '',
      searchHistory: getItem('toutiao-history') || []
    }
  },
  computed: {},
  watch: {
    searchHistory(val) {
      setItem('toutiao-history', val)
      // console.log('haha')
    }
  },
  created() {},
  mounted() {},
  methods: {
    onSearch(val) {
      this.searchText = val
      // 不要有重复历史记录 最新的排在最前面
      const index = this.searchHistory.indexOf(val)
      if (index !== -1) {
        this.searchHistory.splice(index, 1)
      }
      this.searchHistory.unshift(val)
      this.isResultShow = true
    },
    onCancel() {
      this.$router.back()
    }
  }
}
</script>
<style lang="less" scoped>
body {
  background-color: #f5f7f9;
}
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .searchForm {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 2;
  }
}
</style>
